<?php
/**
 * Created by PhpStorm.
 * User: nightelf
 * Date: 2020/1/9
 * Time: 14:35
 */

namespace App\Http\Model;


use Illuminate\Support\Facades\DB;

class RolePermissionModel
{
    const TABLE = 'role_permission';

    /**
     * 获取角色的所有权限
     * @param $roleId
     * @return mixed
     */
    public function getPermission($roleId)
    {
        return DB::table(self::TABLE)
            ->leftJoin('role as r', 'r.id', '=', self::TABLE . '.roleId')
            ->leftJoin('permission as p', 'p.id', '=', self::TABLE . '.permissionId')
            ->where('roleId', $roleId)
            ->where('r.status', 1)
            ->where('p.status', 1)
            ->select('p.*')
            ->get()->toArray();
    }

    /**
     * @param array $data
     * @return mixed
     */
    public function delete(array $data)
    {
        return DB::table(self::TABLE)->where($data)->delete();
    }

    /**
     * 保存角色的权限列表
     * @param array $param
     * @return int
     */
    public function insert(array $param)
    {
        $i = 0;
        $this->delete(['roleId'=>$param['roleId']]);
        foreach ($param['permission'] as $p){
            if (intval($p) && intval($p) > 0){
                DB::table(self::TABLE)->insert(['roleId'=>$param['roleId'],'permissionId'=>intval($p)]);
                $i++;
            }else{
                break;
            }
        }
        return $i;
    }

    /**
     * @param array $param
     * @return mixed
     */
    public function lists(array $param)
    {
        return DB::table(self::TABLE)->where($param)->get()->toArray();
    }
}